﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.TR.Library;
using ZX.TR.Bussiness;
using System.Threading;
using ZX.EHR.Library;
using ZX.BLL.Extend;
using System.Text;
using System.IO;

namespace  ZX.TR.Web
{
    public partial class Questionnaire : BasePage
    {
        #region 字段
        /// <summary>
        /// 开始时间
        /// </summary>
        public static string startTime = "00:00:00";
        /// <summary>
        /// 考试时长
        /// </summary>
        public int longTime = 0;
        /// <summary>
        /// 单题时题目索引
        /// </summary>
        int num = 0; 
        /// <summary>
        /// 倒计时
        /// </summary>
        public string message = ""; 
        /// <summary>
        /// 问卷ID
        /// </summary>
        public string questionnaireID = "";
        public string questionnaireName = "";
        /// <summary>
        /// 页面打开方式：view-查看，Edit-回答问卷
        /// </summary>
        public string flag = "view";
        /// <summary>
        /// 站点地址
        /// </summary>
        public string webSite = "http://" + HttpContext.Current.Request.Url.Host;
        /// <summary>
        /// 业务对象
        /// </summary>
        BTrQuestionnaireSubject bTrQuestionnaireSubject = new BTrQuestionnaireSubject();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!IsPostBack)
            {
                btnPre.Enabled = false;                
                //单题索引
                Session["nums"] = num;
                Session.Timeout = 150;
                V_TrQuestionnaire vtq = new V_TrQuestionnaire();
                questionnaireID = Request.QueryString["id"];
                flag = Request.QueryString["flag"];
                if (flag.ToLower() == "view")
                {
                    plLink.Visible = true;
                    plbegin.Visible = false;
                    plMenu.Visible = true;
                }
                else
                {
                    plLink.Visible = false;
                    plbegin.Visible = true;
                    plMenu.Visible = false;
                }


                if (questionnaireID != "")
                {
                    pnlEn.Enabled = false;
                    vtq = bTrQuestionnaireSubject.GetAllQuestionnaireInfoById(new Guid(questionnaireID));
                    if (vtq != null)
                    {
                        if (HttpContext.Current.Request.Url.Port.ToString() != "")
                        {
                            webSite += ":" + HttpContext.Current.Request.Url.Port.ToString();
                        }
                        webSite += "/TR/Questionnaire.aspx?id={0}&flag=edit";
                        webSite = string.Format(webSite, new Guid(questionnaireID));
                        //txtLink.Text = webSite;
                        lbLink.Text= webSite;
                        lblWjName.Text = vtq.QuestionnaireName;
                        questionnaireName = vtq.QuestionnaireName;
                        lbQuestionnaireID.Text = questionnaireID;
                        txtAim.Text = vtq.QAim;
                        txtDept.Text = vtq.DeptName;
                        txtKnown.Text = vtq.QNotice;
                        //txtPoint.Text = vtq.PointSum.ToString();
                        //txtSum.Text = vtq.SubjectSum.ToString();
                        txtTime.Text = vtq.QTimeLength.ToString();
                        Session["trquestion"] = vtq.TrQuestionnaireID;
                    }
                    Session["times"] = null;
                    bind(Session["trquestion"] == null ? Guid.NewGuid() : new Guid(Session["trquestion"].ToString()), 9999, num);
                    Session["count"] = rptList.Items.Count;
                    if (num == rptList.Items.Count - 1)
                    {
                        btnNext.Enabled = false;
                    }
                }
            }
        }

        private void bind(Guid guid, int topNum, int pageNum)
        {
            DatUser duser = Session["User"] as DatUser;
            IList<V_TrExam> vteList = bTrQuestionnaireSubject.GetExamListById(guid);
            rptList.DataSource = vteList;
            rptList.DataBind();
        }

        #region 计时
        protected void btnBegin_Click(object sender, EventArgs e)
        {
            startTime = DateTime.Now.ToLongTimeString();
            pnlList.Visible = true;
            btnBegin.Enabled = false;
            pnlEn.Enabled = true;
            btnSave.Visible = true;
            rbtnSelect.Enabled = false;
            Session["times"] = DateTime.Now.ToLongTimeString();
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            longTime = Convert.ToInt32(txtTime.Text);
            DateTime date = System.DateTime.Now; //60分钟
            DateTime date2 = Session["times"] == null ? DateTime.Now : Convert.ToDateTime(Session["times"].ToString()).AddMinutes(longTime);
            TimeSpan ts = date2.Subtract(date);
            if (ts.Hours == 0 && ts.Minutes == 0 && ts.Seconds == 0)
            {
                saveExam(true);
                //ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "", "alert('时间到！');closeWins()", true);
                Response.Redirect("Finish.aspx");
            }
            message += ((ts.Hours < 10) ? ("0" + ts.Hours.ToString()) : ts.Hours.ToString());
            message += ":" + (ts.Minutes < 10 ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + ":";
            message += ((ts.Seconds < 10) ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString());
        }
        #endregion

        #region 提交
        /// <summary>
        /// 提交按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (saveExam(false))
                {
                    //ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msg", "javascript:closeWins();", true);
                    Response.Redirect("Finish.aspx");
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 保存问卷调查
        /// </summary>
        /// <param name="bls">是否列表答题</param>
        /// <returns></returns>
        private bool saveExam(bool bls)
        {
            try
            {
                if (!bls)
                {
                    if (GetIstg() == "1")
                    {
                        return false;
                    }
                }

                #region 保存调查用户信息
                string ipaddress = "";
                if (Context.Request.ServerVariables["HTTP_VIA"] != null) // 服务器， using proxy
                {
                    //得到真实的客户端地址
                    ipaddress = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  
                }
                else
                {
                    //如果没有使用代理服务器或者得不到客户端的
                    ipaddress = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); 
                }
                DateTime addtime = DateTime.Now;
                TrUser truser = new TrUser();
                BaseBussnies bbestruser = new BaseBussnies(truser);
                Guid truserid = Guid.NewGuid();
                truser.ID = truserid;
                truser.EmpName = this.EmpName.Value.Trim();
                truser.EmployeeCode = this.EmployeeCode.Value.Trim();
                truser.DeptName = this.DeptName.Value.Trim();
                truser.Company = this.Company.Value.Trim();
                truser.PostName = this.PostName.Value.Trim();
                truser.Phone = this.Phone.Value.Trim();
                truser.MobilePhone = this.MobliePhone.Value.Trim();
                truser.EMail = this.EMail.Value.Trim();
                truser.IPAdderss = ipaddress;
                bbestruser.Insert();
                #endregion

                #region 保存答案
                for (int i = 0; i < rptList.Items.Count; i++)
                {
                    TextBox txtAnswer = rptList.Items[i].FindControl("txtAnswer") as TextBox;
                    HiddenField subjectInfoID = rptList.Items[i].FindControl("subjectInfoID") as HiddenField;
                    HiddenField questionnaireSubjectID = rptList.Items[i].FindControl("questionnaireSubjectID") as HiddenField;
                    RadioButtonList rbl = rptList.Items[i].FindControl("rbtnAnswer") as RadioButtonList;
                    CheckBoxList chk = rptList.Items[i].FindControl("chkAnswer") as CheckBoxList;
                    TextBox txtExplain = rptList.Items[i].FindControl("txtExplain") as TextBox;
                    Label lblType = rptList.Items[i].FindControl("lblType") as Label;

                    if (questionnaireSubjectID != null)
                    {
                        TrQuestionnaireAnswer tqa = new TrQuestionnaireAnswer();
                        BaseBussnies bbestqa = new BaseBussnies(tqa);
                        tqa.ID = Guid.NewGuid();
                        tqa.TrUserID = truserid;
                        tqa.TrQuestionnaireID = new Guid(lbQuestionnaireID.Text);
                        tqa.TrSubjectInfoID = new Guid(subjectInfoID.Value);
                        tqa.AddIP = ipaddress;
                        tqa.AddTime = addtime;

                        if (txtExplain != null && txtExplain.Text.Length > 0)
                        {
                            tqa.Answer = txtExplain.Text;
                        }
                        switch (lblType.Text)
                        {
                            case "填空题":
                                if (txtAnswer != null && txtAnswer.Text != "")
                                {
                                    tqa.Answer = txtAnswer.Text;
                                    bbestqa.Insert();
                                }
                                break;
                            case "单选题":
                                if (txtAnswer != null && txtAnswer.Text != "")
                                {
                                    tqa.Answer = txtAnswer.Text;
                                }
                                if (rbl != null && rbl.SelectedIndex != -1)
                                {
                                    tqa.TrSubjectItemID = new Guid(rbl.SelectedItem.Value);
                                    bbestqa.Insert();
                                }
                                break;
                            case "判断题":
                                if (rbl != null && rbl.SelectedIndex != -1)
                                {
                                    tqa.Answer = rbl.SelectedItem.Value;
                                    bbestqa.Insert();
                                }
                                break;
                            case "多选题":
                                if (txtAnswer != null && txtAnswer.Text != "")
                                {
                                    tqa.Answer = txtAnswer.Text;
                                }
                                if (chk != null && chk.SelectedIndex != -1)
                                {
                                    for (int j = 0; j < chk.Items.Count; j++)
                                    {
                                        if (chk.Items[j].Selected)
                                        {
                                            tqa.TrSubjectItemID = new Guid(chk.Items[j].Value);
                                            tqa.ID = Guid.NewGuid();
                                            bbestqa.Insert();
                                        }
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                #endregion
                return true;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 是否可以跳过
        /// </summary>
        private string GetIstg()
        {
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                TextBox te = rptList.Items[i].FindControl("txtAnswer") as TextBox;
                RadioButtonList rbl = rptList.Items[i].FindControl("rbtnAnswer") as RadioButtonList;
                CheckBoxList chk = rptList.Items[i].FindControl("chkAnswer") as CheckBoxList;
                HiddenField IsJumpOver = rptList.Items[i].FindControl("IsJumpOver") as HiddenField;
                if (IsJumpOver.Value != "Y")
                {
                    string tempJump = "";
                    if (te != null && te.Text != "")
                    {
                        tempJump = te.Text;
                    }
                    else if (rbl != null && rbl.SelectedIndex != -1)
                    {
                        tempJump = rbl.SelectedItem == null ? "" : rbl.SelectedItem.Text;
                    }
                    else if (chk != null && chk.SelectedIndex != -1)
                    {
                        string chkTemp = "";
                        for (int j = 0; j < chk.Items.Count; j++)
                        {
                            if (chk.Items[j].Selected)
                            {
                                if (j == chk.SelectedIndex)
                                {
                                    chkTemp += chk.Items[j].Text;
                                }
                                else { chkTemp += "," + chk.Items[j].Text; }
                            }
                        }
                        tempJump = chkTemp;
                    }
                    if (tempJump == "")
                    {
                        lblShow.Text = "<font color='Red'>第" + (i + 1) + "题为必填题，不能跳过</font>";
                        return "1";
                    }
                }
            } return "";
        }

        #endregion

        #region 上\下题事件
        /// <summary>
        /// 上一题按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPre_Click(object sender, EventArgs e)
        {
            Session["nums"] = Convert.ToInt32(Session["nums"].ToString()) - 1;
            num = Convert.ToInt32(Session["nums"].ToString());
            btnNext.Enabled = true;
            if (num == 0)
            {
                btnPre.Enabled = false;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                if (i == num)
                {
                    this.rptList.Items[i].Visible = true;
                }
                else { this.rptList.Items[i].Visible = false; }
            }
        }

        /// <summary>
        /// 下一题按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNext_Click(object sender, EventArgs e)
        {

            //HiddenField IsJumpOver = rptList.Items[0].FindControl("IsJumpOver") as HiddenField;
            //TextBox te = rptList.Items[0].FindControl("txtAnswer") as TextBox;
            //if (IsJumpOver != null && te != null && IsJumpOver.Value != "Y" && te.Text.Trim() == "")
            //{
            //    Page.ClientScript.RegisterStartupScript(GetType(), "",
            //        "<script>alert('该题为必填题，不能跳过！')</script>");
            //} 
            btnNext.Enabled = true;
            if (Convert.ToInt32(Session["nums"].ToString()) == (Convert.ToInt32(Session["count"].ToString()) - 2))
            {
                btnNext.Enabled = false; num = Convert.ToInt32(Session["nums"].ToString()) + 1; Session["nums"] = Convert.ToInt32(Session["nums"].ToString()) + 1;
            }
            else
            {
                Session["nums"] = Convert.ToInt32(Session["nums"].ToString()) + 1; num = Convert.ToInt32(Session["nums"].ToString());
            }


            btnPre.Enabled = true;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                if (i == num)
                {
                    this.rptList.Items[i].Visible = true;
                }
                else
                {
                    this.rptList.Items[i].Visible = false;
                }
            }
        }
        #endregion

        #region 答题方式
        /// <summary>
        /// 答题方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rbtnSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbtnSelect.SelectedIndex == 0)
            {
                btnNext.Visible = false;
                btnPre.Visible = false;
                for (int i = 0; i < rptList.Items.Count; i++)
                {
                    this.rptList.Items[i].Visible = true;
                }
            }
            else
            {

                for (int i = 0; i < rptList.Items.Count; i++)
                {
                    if (i == 0)
                    {
                        this.rptList.Items[0].Visible = true;
                    }
                    else { this.rptList.Items[i].Visible = false; }
                }
                btnNext.Visible = true;
                btnPre.Visible = true;


            }
        }
        #endregion

        #region 生成问卷题目
        /// <summary>
        /// 控件绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblType = e.Item.FindControl("lblType") as Label;
            TextBox txtAnswer = e.Item.FindControl("txtAnswer") as TextBox;
            HiddenField subjectInfoID = e.Item.FindControl("subjectInfoID") as HiddenField;
            Panel pnExplain = e.Item.FindControl("pnExplain") as Panel;
            Panel plAnswer = e.Item.FindControl("plAnswer") as Panel;

            if (lblType != null && lblType.Text == "判断题")
            {
                RadioButtonList rbl = e.Item.FindControl("rbtnAnswer") as RadioButtonList;
                if (rbl != null)
                {
                    rbl.Visible = true;
                    bindYesOrNo(rbl);
                }
                txtAnswer.Visible = false;
            }
            else if (lblType != null && (lblType.Text == "单选题" || lblType.Text == "多选题"))
            {
                Repeater rptItem = e.Item.FindControl("rptItem") as Repeater;
                TextBox txtExplain = e.Item.FindControl("txtExplain") as TextBox;
                if (subjectInfoID != null)
                {
                    rptItem.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(new Guid(subjectInfoID.Value));
                    rptItem.DataBind();
                    if (lblType.Text == "单选题")
                    {
                        RadioButtonList rbl = e.Item.FindControl("rbtnAnswer") as RadioButtonList;
                        if (rbl != null)
                        {
                            rbl.Visible = true;
                            bindSingleSubject(rbl, new Guid(subjectInfoID.Value));
                            for (int i = 0; i < rbl.Items.Count; i++)
                            {
                                IsVisibleExplain(rbl.Items[i].Value, txtExplain, pnExplain);
                            }
                        }
                    }
                    else if (lblType.Text == "多选题")
                    {
                        CheckBoxList chk = e.Item.FindControl("chkAnswer") as CheckBoxList;
                        if (chk != null)
                        {
                            chk.Visible = true;
                            bindCheckSubject(chk, new Guid(subjectInfoID.Value));
                            for (int i = 0; i < chk.Items.Count; i++)
                            {
                                IsVisibleExplain(chk.Items[i].Value, txtExplain, pnExplain);
                            }
                        }
                    }
                }
                txtAnswer.Visible = false;
            }

            if (plAnswer != null)
            {
                if (flag.ToLower() == "view")
                {
                    plAnswer.Visible = false;
                }
                else
                {
                    plAnswer.Visible = true;
                }
            }
        }

        /// <summary>
        /// 单选、多选题的选项有“其它”时，要出现文本输入框
        /// </summary>
        /// <param name="answer"></param>
        /// <param name="txtExplain"></param>
        private void IsVisibleExplain(string answer, TextBox txtExplain, Panel pnExplain)
        {
            if (answer == "其他" || answer == "其它" || answer == "其她")
            {
                pnExplain.Visible = true;
                txtExplain.Visible = true;
            }
        }

        /// <summary>
        /// 初始化单选题选项
        /// </summary>
        /// <param name="rbl"></param>
        /// <param name="gd"></param>
        private void bindSingleSubject(RadioButtonList rbl, Guid gd)
        {
            if (gd == null)
            {
                gd = Guid.NewGuid();
            }
            rbl.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(gd);
            rbl.DataTextField = "itemcode";
            rbl.DataValueField = "TrSubjectItemID";
            rbl.DataBind();
        }

       /// <summary>
       /// 初始化多选是选项
       /// </summary>
       /// <param name="chk"></param>
       /// <param name="gd"></param>
        private void bindCheckSubject(CheckBoxList chk, Guid gd)
        {
            if (gd == null)
            {
                gd = Guid.NewGuid();
            }
            chk.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(gd);
            chk.DataTextField = "itemcode";
            chk.DataValueField = "TrSubjectItemID";
            chk.DataBind();
        }

        /// <summary>
        /// 初始化判断题选项
        /// </summary>
        /// <param name="rbl">RadioButtonList控件名</param>
        private void bindYesOrNo(RadioButtonList rbl)
        {
            ListItem liYes = new ListItem();
            liYes.Text = "对";
            liYes.Value = "对";
            rbl.Items.Add(liYes);
            ListItem liNo = new ListItem();
            liNo.Text = "错";
            liNo.Value = "错";
            rbl.Items.Add(liNo);
        }

        /// <summary>
        /// 返回是否必填
        /// </summary>
        /// <param name="obj">Y/N</param>
        /// <returns></returns>
        protected string GetIsJump(object obj)
        {
            if (obj.ToString() != "Y")
            {
                return "<font color='Red'>*必填</font>";
            }
            return "";
        }
        #endregion

    }
}